import {Button, Form, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {OpCaseManage} from "@/services/api-functions";
import {SYS_ENUMS} from "@/utils/constants";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {history} from "@@/core/history";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import {ModalForm, ProFormSelect, ProFormTextArea} from "@ant-design/pro-form";


export const caseAudit = async (fields: any, select: any, callBack?: Function) => {
  if (!select) return false;
  try {
    if (isSuccess((await OpCaseManage.audit({
      businessId: select.id,
      auditOperate: fields.auditOperate,
      remark: fields.remark,
      flowType: 'CASE_AUDIT',
    }))?.code)) {
      message.success(fields.auditOperate === SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value ? '审核通过' : '审核拒绝');
      callBack?.();
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

export const caseDelete = async (select: any) => {
  if (!select) return false;
  try {
    message.loading('正在删除');
    if (isSuccess((await OpCaseManage.delete(select.id))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const CaseList: React.FC<any> = ({}) => {
  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL' | 'ING' | 'PASS' | 'REFUSE'>('ING');
  const [countInfo, setCountInfo] = useState<{ ALL: number, ING: number, PASS: number, REFUSE: number }>({
    ALL: 0,
    ING: 0,
    PASS: 0,
    REFUSE: 0,
  });
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const columns: ProColumns[] = [
    {
      title: '封面',
      dataIndex: 'cover',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
      render: (dom, record) => record.cover?<img src={record.cover?.url} alt="" style={{maxWidth:107, maxHeight: 58}}/>:'-',
    },
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 300,
    },
    {
      title: '设计师',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '设计师等级',
      dataIndex: 'customizeLevel',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
      valueEnum: SYS_ENUMS.LEVEL,
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      valueEnum: SYS_ENUMS.RESOURCE_AUDIT_STATE,
      width: 100,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '服务客户',
      dataIndex: 'serveCustomers',
      ellipsis: true,
      width: 200,
    },
    {
      title: '案例价格',
      dataIndex: 'casePrice',
      width: 130,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '浏览量',
      dataIndex: 'browseNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '点赞数',
      dataIndex: 'greatNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '收藏数',
      dataIndex: 'focusNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '评论数',
      dataIndex: 'replyNum',
      ellipsis: true,
      hideInSearch: true,
      width: 100,
    },
    {
      title: '发布时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      fixed: 'right',
      hideInForm: true,
      render: (_, record) => [
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => {
               if (await caseDelete(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >删除</a>,
        <a key="edit" href={`/custom/case/detail/${record?.id}`}>详情</a>,
        (
          record.auditState === SYS_ENUMS.RESOURCE_AUDIT_STATE.ING.value
            ? <a key="edit" onClick={() => {
              setCurrentRow(record)
              auditFormRef?.resetFields()
              handleAuditVisible(true)
            }}>审核</a> : <span style={{color: 'gray'}}>审核</span>
        ),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='ING'>待审核 {countInfo?.ING ?? 0}</Radio.Button>
          <Radio.Button value='PASS'>已通过 {countInfo?.PASS ?? 0}</Radio.Button>
          <Radio.Button value='REFUSE'>未通过 {countInfo?.REFUSE ?? 0}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button onClick={() => history.push('/article/comments')}>评论列表</Button>,
        ]}
        request={async (params) => {

          const query = {...params}
          if (auditState !== 'ALL') {
            query.auditState = auditState
          }

          const {data: {data, total}, code}: any = await OpCaseManage.pageQuery(query);

          const res = await OpCaseManage.countInfo();

          if (isSuccess(res.code)) {
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />

      <ModalForm
        title={`审核【${currentRow?.title}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await caseAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
    </PageContainer>
  );
};

export default CaseList;
